package collector

import (
	"database/sql"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var logRE = regexp.MustCompile(`.+\.(\d+)$`)

// 验证可用性
func vaildPrometheusName(s string) string {
	//匹配毫秒（ms）
	msRE := regexp.MustCompile(`\(ms\)`)
	s = msRE.ReplaceAllString(s, "")
	//匹配括号 `/(/)` 去除括号
	leftParenthesisRE := regexp.MustCompile(`\(`)
	s = leftParenthesisRE.ReplaceAllString(s, " ")
	rightParenthesisRE := regexp.MustCompile(`\)`)
	s = rightParenthesisRE.ReplaceAllString(s, "")
	nameRe := regexp.MustCompile("([^a-zA-Z0-9_/])")
	s = nameRe.ReplaceAllString(s, "_")
	s = strings.ToLower(s)
	return s
}

// 解析sql字段返回float64
func parseStatus(data sql.RawBytes) (float64, bool) {
	dataString := strings.ToLower(string(data))
	switch dataString {
	case "yes", "on":
		return 1, true
	case "no", "off", "disabled":
		return 0, true
	// SHOW SLAVE STATUS Slave_IO_Running can return "Connecting" which is a non-running state.
	case "connecting":
		return 0, true
	// SHOW GLOBAL STATUS like 'wsrep_cluster_status' can return "Primary" or "non-Primary"/"Disconnected"
	case "primary":
		return 1, true
	case "non-primary", "disconnected":
		return 0, true
	}
	if ts, err := time.Parse("Jan 02 15:04:05 2006 MST", string(data)); err == nil {
		return float64(ts.Unix()), true
	}
	if ts, err := time.Parse("2006-01-02 15:04:05", string(data)); err == nil {
		return float64(ts.Unix()), true
	}
	if logNum := logRE.Find(data); logNum != nil {
		value, err := strconv.ParseFloat(string(logNum), 64)
		return value, err == nil
	}
	value, err := strconv.ParseFloat(string(data), 64)
	return value, err == nil
}
